package com.zzyl.nursing.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 入住Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-26
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper,CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private ContractMapper contractMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;


    @Override
    public CheckInDetailVo detail(Long id) {
//        查询4张表数据
        CheckIn checkIn = checkInMapper.selectById(id);
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery()
                .eq(CheckInConfig::getCheckInId,id));
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery()
                .eq(Contract::getElderId,checkIn.getElderId())
                .eq(Contract::getStatus,1)
                .orderByDesc(Contract::getCreateTime)
                .last("limit 1"));
        Elder elder = elderMapper.selectById(checkIn.getElderId());

//        vo转换
        CheckInDetailVo vo = new CheckInDetailVo();
        CheckInElderVo checkInElderVo = new CheckInElderVo();

        BeanUtils.copyProperties(elder,checkInElderVo);
        vo.setCheckInElderVo(checkInElderVo);
//          家属

        String remark = checkIn.getRemark();
        if (!Objects.isNull(remark)){
            List<ElderFamilyVo> elderFamilyVoList = JSONUtil.toList(remark, ElderFamilyVo.class);
            vo.setElderFamilyVoList(elderFamilyVoList);

        }
//        转换
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfigVo,checkInConfigVo);
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        vo.setCheckInConfigVo(checkInConfigVo);

//        合同
        vo.setContract(contract);


        return vo;
    }

    @Override
    public void apply(CheckInApplyDto dto) {
        // 1. 校验老人身份证号
        String idCardNo = dto.getCheckInElderDto().getIdCardNo();
        if (StringUtils.isBlank(idCardNo)) {
            throw new BaseException("老人身份证号不能为空");
        }

        // 2. 检查老人是否已入住（状态非0/5）
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, idCardNo));

        if (elder != null) {
            Integer status = elder.getStatus();
            if (status == null) {
                throw new BaseException("老人状态异常，请联系管理员");
            }
            if (status != 0 && status != 5) {
                throw new BaseException("老人已入住（当前状态：" + status + "）");
            }
        }

        // 3. 校验床位有效性并占用床位
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        if (bed == null) {
            throw new BaseException("所选床位不存在");
        }

        int count = bedMapper.updateBedStatus(bed.getId(), 1); // 明确更新为占用状态
        if (count == 0) {
            throw new BaseException("床位已被占用，请重新选择");
        }

        // 4. 新增或更新老人信息
        if (elder != null) {
            // 更新老人信息（补充床位和状态）
            elder.setStatus(1);
            elder.setBedId(bed.getId());
            elder.setBedNumber(bed.getBedNumber());
            elderMapper.updateById(elder);
        } else {
            // 新增老人信息
            elder = new Elder();
            BeanUtils.copyProperties(dto.getCheckInElderDto(), elder);
            elder.setStatus(1);
            elder.setBedId(bed.getId());
            elder.setBedNumber(bed.getBedNumber());
            elder.setCreateTime(new Date());
            elderMapper.insert(elder);
        }

        // 5. 新增签约合同（统一日期类型处理）
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());

        // 处理开始日期（统一使用LocalDateTime）
        LocalDateTime startDate = dto.getCheckInConfigDto().getStartDate();
        contract.setStartDate(startDate);

        // 获取 LocalDateTime 类型的结束时间
        LocalDateTime endDateTime = dto.getCheckInConfigDto().getEndDate();

// 将 LocalDateTime 转换为 Date 类型
        Date endDate = Date.from(endDateTime.atZone(ZoneId.systemDefault()).toInstant());

// 调用 setEndDate 方法
        contract.setEndDate(endDate);

        // 设置签约日期
        contract.setSignDate(new Date());

        // 设置合同状态（直接使用LocalDateTime比较）
        contract.setStatus(startDate.isAfter(LocalDateTime.now()) ? 1L : 0L);

        contractMapper.insert(contract);

        // 6. 新增入住信息
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkIn);
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(1);
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        checkIn.setCreateTime(new Date());
        checkInMapper.insert(checkIn);

        // 7. 新增入住配置
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfig.setCreateTime(new Date());
        checkInConfigMapper.insert(checkInConfig);
    }




    public void applyBackup(CheckInApplyDto dto) {
        //1、检查老人是否已经入住，如果入住了，直接结束(非0/5)
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery()
                .eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo()));
        if(elder!=null && elder.getStatus().intValue()!=0 && elder.getStatus().intValue()!=5){
            throw new BaseException("老人已入住");
        }

        //2、占用床位-status=1
        int count = bedMapper.updateBedStatus(dto.getCheckInConfigDto().getBedId(), 1);
        //3、新增或者修改老人信息(无老人数据，执行新增，有老人数据，执行修改)
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        if(elder!=null){
            //修改
            elderMapper.updateById(elder);
        }else{
            if(elder==null){
                elder = new Elder();
                elder.setCreateTime(new Date());
            }
            BeanUtils.copyProperties(dto.getCheckInElderDto(),elder);
            elder.setStatus(1);
            elder.setBedId(bed.getId());
            elder.setBedNumber(bed.getBedNumber());
            //新增
            elderMapper.insert(elder);
        }

        //4、新增签约办理
        Contract contract = new Contract();
        BeanUtils.copyProperties(dto.getCheckInContractDto(),contract);
        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber()); //合同编号
        contract.setStartDate(dto.getCheckInConfigDto().getStartDate());  //开始时间



        // 获取 LocalDateTime 类型的结束时间
        LocalDateTime endTime = dto.getCheckInConfigDto().getEndDate();

// 将 LocalDateTime 转换为 Date 类型
        Date endDateValue = Date.from(endTime.atZone(ZoneId.systemDefault()).toInstant());

// 调用 setEndDate 方法
        contract.setEndDate(endDateValue);

        contract.setStatus((long) (contract.getStartDate().isAfter(LocalDateTime.now())? 1 :0)); //状态

        contractMapper.insert(contract);

        //5、新增入住信息
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkIn);
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(1);
        //家属信息->remark
        checkIn.setRemark(JSONUtil.toJsonStr(dto.getElderFamilyDtoList()));
        checkInMapper.insert(checkIn);

        //6、新增入住配置
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(),checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        checkIn.setCreateTime(DateUtils.getNowDate());
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        checkIn.setUpdateTime(DateUtils.getNowDate());
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteByIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }


}
